package com.gupao.jly521.proxy.jdk;

import com.gupao.jly521.entity.Person;
import com.gupao.jly521.entity.ProgramPerson;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 *  JDK动态代理只能针对实现了接口的类生成代理；
 * @author Jly
 * @date 2018/8/22  16:52
 */
public class JdkProxy implements InvocationHandler {

    private Person person;

    public Object getInstance(Person person){
        if(person == null){
            throw new NullPointerException("Person 对象为空！！！");
        }
        this.person = person;
        Class<?> clazz = person.getClass();
        return Proxy.newProxyInstance(clazz.getClassLoader(),clazz.getInterfaces(),this);
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        System.out.println("jdk 动态代理执行前！！！");
        Object res = method.invoke(person,args);
        System.out.println("jdk 动态代理执行后！！！");
        if(res != null ){
            return  res;
        }
        return null;
}

    public static void main(String[] args) {
        Person person = (Person) new JdkProxy().getInstance(new ProgramPerson());
        person.findJob(); //不带返回参数
        System.out.println("--------------------------------------");
//        String girl = person.findGirlFriend();  //带返回参数
//        System.out.println(girl);
    }
}
